package com.zxd.interview.jmm;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 适用 volatile 的场景
 */
public class UseVolatile implements Runnable{

    volatile boolean flag;

    AtomicInteger realA = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException {
        UseVolatile useVolatile = new UseVolatile();
        Thread thread1 = new Thread(useVolatile);
        thread1.start();
        Thread thread2 = new Thread(useVolatile);
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println("useVolatile.flag => "+ useVolatile.flag);
        System.out.println("AtomicInteger.realA => "+ useVolatile.realA.get());


    }/**
     适用场景：只有变量的赋值操作
     */


    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            setFlag();
            realA.incrementAndGet();
        }
    }

    private void setFlag() {
        flag = true;
    }

}
